<template>
  <div style="width: 100%;height: 100%;position: relative;padding-top: 54px">
    <v-app-bar flat
               app
               color="white"
               style="z-index: 1;padding-top: 6px;left: 0;"
               height="54"
               absolute
    >
      <v-toolbar-title>分类 Category</v-toolbar-title>
      <v-divider
        class="mx-4"
        inset
        vertical
      ></v-divider>
      <v-spacer></v-spacer>
      <v-dialog v-model="dialog" max-width="500px">
        <v-card>
          <v-card-title>
            <span class="headline">{{ formTitle }}</span>
          </v-card-title>

          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12" sm="12" md="12">
                  <v-text-field v-model="editedItem.name"
                                ref="categoryNameInputRef"
                                :rules="[() => !!editedItem.name || '请输入分类名称']"
                                label="分类名称"></v-text-field>
                </v-col>
              </v-row>
            </v-container>
          </v-card-text>

          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="pink darken-1" text @click="close">取消</v-btn>
            <v-btn color="blue darken-1" text @click="save">确认</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-app-bar>
    <div style="z-index: 0;height: 100%;padding: 20px">
      <v-simple-table fixed-header
                      height="100%"
      >
        <template v-slot:default>
          <thead>
          <tr>
            <th class="text-left" v-for="(v,i) in headers" :key="i">{{ v.text }}</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="item in categoryList" :key="item.name">
            <td>{{ item._id }}</td>
            <td>{{ item.name }}</td>
            <td>{{ item.articleCount }}</td>
            <td>
              <v-icon
                small
                class="mr-2"
                @click="editItem(item)"
              >
                mdi-pencil
              </v-icon>
              <v-icon
                small
                @click="deleteItem(item)"
              >
                mdi-delete
              </v-icon>
            </td>
          </tr>
          </tbody>
        </template>
      </v-simple-table>
    </div>
    <v-btn
      color="pink"
      dark
      fab
      fixed
      right
      bottom
      class="mb-4"
      @click="dialog=true"
    >
      <v-icon>mdi-plus</v-icon>
    </v-btn>
  </div>
</template>

<script>
import {
  CreateCategory,
  DeleteCategory,
  GetAllCategory,
  GetArticleCountUnderCategory,
  UpdateOneCategory
} from '../api/blog-api'

export default {
  name: 'CategoryManager',
  data: () => ({
    dialog: false,
    headers: [
      {
        text: 'ID',
        align: 'start',
        value: '_id',
      },
      {
        text: '分类名称',
        value: 'name'
      },
      {
        text: '文章数',
        value: 'articleCount'
      },
      {
        text: '操作',
        value: 'manager'
      }
    ],
    categoryList: [],
    editedIndex: -1,
    editedItem: {
      name: ''
    },
    defaultItem: {
      name: ''
    }
  }),

  computed: {
    formTitle () {
      return this.editedIndex === -1 ? '新增分类' : '编辑分类'
    },
  },

  watch: {
    dialog (val) {
      val || this.close()
    },
  },

  created () {
    this.initialize()
  },

  methods: {
    initialize () {
      this.categoryList = []
      GetAllCategory().then(res => {
        this.categoryList = res.data
      }).catch(err => {
        console.log(err)
      })
      GetArticleCountUnderCategory()
    },

    editItem (item) {
      this.editedIndex = this.categoryList.indexOf(item)
      this.editedItem = Object.assign({}, item)
      this.dialog = true
    },

    deleteItem (item) {
      const index = this.categoryList.indexOf(item)
      if (confirm('确认删除该分类？')) {
        DeleteCategory(this.editedItem).then(res => {
          this.categoryList.splice(index, 1)
        }).catch(err => {
        })
      }
    },

    close () {
      this.dialog = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    save () {
      if (!this.editedItem.name) {
        this.$refs.categoryNameInputRef.validate(true)
        return
      }
      if (this.editedIndex > -1) {
        UpdateOneCategory(this.editedItem).then(res => {
          Object.assign(this.categoryList[this.editedIndex], res.data)
        }).catch(err => {
          console.log(err)
        }).finally(() => {
          this.close()
        })
      } else {
        CreateCategory([this.editedItem]).then(res => {
          this.categoryList.push(...res.data)
        }).catch(err => {
          console.log(err)
        }).finally(() => {
          this.close()
        })
      }

    },
  }
}
</script>

<style scoped>

</style>
